# -*- coding:utf-8 -*-
__author__ = 'weiguang.zuo'

import sys
import json

"""
    功能：ETL脚本
         读取包头市各大队划界图数据
"""

# reload(sys)
# sys.setdefaultencoding('utf-8')
try:
    from osgeo import ogr, osr, gdal
except:
    print 'ERROR: cannot find GDAL/OGR modules'
    sys.exit()

# 注册驱动
ogr.RegisterAll()
# 为了支持中文路径，请添加下面这句代码
gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "NO")
# 为了使属性表字段支持中文，请添加下面这句
gdal.SetConfigOption("SHAPE_ENCODING", "")

def read_PT_REALATION_Stop():

    print "read mif......"
    featureCollection = []

    mifPath = "E:\\baotou_mif"
    filePath = mifPath + "\\baotou.TAB"
    driver = ogr.GetDriverByName('MapInfo File')
    dataSource = driver.Open(filePath, 0)
    layerCount = dataSource.GetLayerCount()
    for i in range(layerCount):
        layer = dataSource.GetLayer(i)
        layer.ResetReading()
        feature = layer.GetNextFeature()
        featureCount = 0
        while feature:
            daduiname = feature.GetField("dadui_name")
            geom = feature.GetGeometryRef()
            # geojson
            geom_json_str = geom.ExportToJson()
            geometry_json = json.loads(geom_json_str, encoding="utf-8")
            # wkt
            # geoFromWkt = geom.ExportToWkt()

            feature_result = {"type": "FeatureCollection",
                                  "features": [
                                      {"type": "Feature",
                                       "geometry": geometry_json,
                                       "properties": {"daduiname": daduiname}
                                       }
                                  ]
                              }
            featureCollection.append(feature_result)

            print daduiname.decode("GBK").encode("utf-8"), geometry_json

            feature = layer.GetNextFeature()
            featureCount += 1
        if feature:
            feature.Destroy()

    dataSource.Destroy()

    write_txt_file(featureCollection)

def write_txt_file(featureCollection):
    # text = json.dumps(featureCollection, ensure_ascii=False).decode("GBK").encode("utf-8")
    text = json.dumps(featureCollection, ensure_ascii=False)
    print text
    with open("E:\\baotou_mif\\geojson.txt", "w") as writer:
        writer.write(text)


def printDriverName():
    dsCount = ogr.GetDriverCount()
    print dsCount
    for i in range(dsCount):
        ds = ogr.GetDriver(i)
        driverName = ds.GetName()
        print driverName


if __name__ == "__main__":
    # printDriverName()

    # 读取站点关系表
    read_PT_REALATION_Stop()
    print "process done!!"

